package xin.lhuo.we.server.service.impl;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xin.lhuo.we.server.constant.HttpConstant;
import xin.lhuo.we.server.dao.*;
import xin.lhuo.we.server.entity.*;
import xin.lhuo.we.server.enums.ResultEnum;
import xin.lhuo.we.server.exception.WeException;
import xin.lhuo.we.server.properties.QiNiuProperties;
import xin.lhuo.we.server.service.IHomeService;
import xin.lhuo.we.server.utils.DateUtils;
import xin.lhuo.we.server.utils.OkHttpUtil;
import xin.lhuo.we.server.utils.QiNiuUtil;
import xin.lhuo.we.server.vo.HomeVo;
import xin.lhuo.we.server.vo.WeatherVo;
import xin.lhuo.we.server.voutils.WeatherUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author Lhuo
 * @date 2019/5/22 0:05
 */
@Service(value = "homeServer")
@Slf4j
public class HomeServiceImpl implements IHomeService {
    private final PhotoMapper photoMapper;
    private final AlbumMapper albumMapper;
    private final WeatherMapper weatherMapper;
    private final FolderMapper folderMapper;
    private final DocumentMapper documentMapper;
    private final QiNiuProperties qiNiuProperties;

    public HomeServiceImpl(PhotoMapper photoMapper,
                           AlbumMapper albumMapper,
                           WeatherMapper weatherMapper,
                           FolderMapper folderMapper,
                           DocumentMapper documentMapper,
                           QiNiuProperties qiNiuProperties) {
        this.photoMapper = photoMapper;
        this.albumMapper = albumMapper;
        this.weatherMapper = weatherMapper;
        this.folderMapper = folderMapper;
        this.documentMapper = documentMapper;
        this.qiNiuProperties = qiNiuProperties;
    }

    @Override
    public HomeVo getHomeVo(Integer userId) {
        HomeVo homeVo = new HomeVo();
        homeVo.setAlbumCount(albumMapper.countByUserId(userId));
        homeVo.setPhotoCount(photoMapper.countByUserId(userId));
        homeVo.setFolderCount(folderMapper.countByUserId(userId));
        homeVo.setDocumentCount(documentMapper.countByUserId(userId));
        return homeVo;
    }

    @Override
    public List<Photo> recentlyUpdatePhoto(Integer userId) {
        List<Photo> photoList = photoMapper.selectRecentlyPhotoByUserId(userId);
        photoList.forEach(photo -> {
            photo.setThumbnailUrl(QiNiuUtil.getDownloadUrl(qiNiuProperties, photo.getUrl() + "-thumbnail"));
            photo.setUrl(QiNiuUtil.getDownloadUrl(qiNiuProperties, photo.getUrl()));
        });

        return photoList;
    }

    @Override
    public List<Document> recentlyUpdateDocument(Integer userId) {
        List<Document> documentList =  documentMapper.selectRecentlyDocumentByUserId(userId);
        documentList.forEach(document -> {
            String url = QiNiuUtil.getDownloadUrl(qiNiuProperties,qiNiuProperties.getBaseUrl()+document.getKey());
            document.setUrl(url);
        });
        return documentList;
    }

    @Override
    public WeatherVo getWeather(String ip) {
        String getLocationUrl = HttpConstant.BAI_DU_BY_IP_URL + "&ak=" + HttpConstant.BAI_DU_MAP_AK + "&ip=" + ip;
        Gson gson = new Gson();
        String nowDate = DateUtils.getNowDate();
        //判断当天，同一个ip的天气信息是否已经缓存，如已存在直接返回
        Weather weather = null;
        weather = weatherMapper.getWeatherByIpAndDate(ip, nowDate);
        if (weather != null) {
            return gson.fromJson(weather.getInfo(), WeatherVo.class);
        }
        try {
            String result = OkHttpUtil.get(getLocationUrl);
            BaiDuLocation baiDuLocation = gson.fromJson(result, BaiDuLocation.class);
            if (baiDuLocation.getStatus() != 0) {
                //获取城市信息失败 返回北京的信息
                BaiDuLocation.ContentBean contentBean = new BaiDuLocation.ContentBean();
                BaiDuLocation.ContentBean.PointBean pointBean = new BaiDuLocation.ContentBean.PointBean();
                pointBean.setX("125.293406");
                pointBean.setY("43.832586");
                contentBean.setPoint(pointBean);
                contentBean.setAddress("长春市");
                baiDuLocation.setContent(contentBean);
            }

            //判断当天，同一个城市的天气信息是否已经缓存，如已存在直接返回
            weather = weatherMapper.getWeatherByCityAndDate(baiDuLocation.getContent().getAddress(), nowDate);
            if (weather != null) {
                return gson.fromJson(weather.getInfo(), WeatherVo.class);
            }
            String x = baiDuLocation.getContent().getPoint().getX();
            String y = baiDuLocation.getContent().getPoint().getY();
            String weatherUrl = HttpConstant.CAI_YUN_WEATHER_URL_01 + x + ',' + y + HttpConstant.CAI_YUN_WEATHER_URL_02;
            String weatherResult = OkHttpUtil.get(weatherUrl);
            CaiYunSimpleWeather simpleWeather = gson.fromJson(weatherResult, CaiYunSimpleWeather.class);
            if ("ok".equals(simpleWeather.getStatus())) {
                WeatherVo weatherVo = WeatherUtils.caiYunSimpleWeatherToWeather(simpleWeather, baiDuLocation.getContent().getAddress());
                weather = new Weather();
                weather.setCity(baiDuLocation.getContent().getAddress());
                weather.setIp(ip);
                weather.setInfo(gson.toJson(weatherVo));
                weather.setDate(DateUtils.getNowDate());
                weatherMapper.saveWeather(weather);
                return weatherVo;
            } else {
                // todo 获取天气信息失败
                throw new WeException(ResultEnum.WEATHER_FAIL);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new WeException(ResultEnum.WEATHER_FAIL);
        }
    }


}
